package com.rocksea.app.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.mor.dataacquisition.DataAcquisition;
import com.mor.dataacquisition.net.DataCallBack;
import com.mor.dataacquisition.net.parsedData.ResponseData;
import com.rocksea.app.Account;
import com.rocksea.app.R;
import com.rocksea.app.db.DbCenter;
import com.rocksea.app.db.image.ImageTable;
import com.rocksea.app.event.NotificationImage;
import com.rocksea.app.http.UpDateRandomCodeTask;
import com.rocksea.app.utils.FileHelper;
import com.rocksea.app.utils.UiUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;

/**
 * Created by 吴志华 on 2017/10/18.
 *
 */

public class PhotoViewActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener
{

    private ViewPager mImageViewPager;
    private TextView mRemake;
    private TextView mTime;
    private TextView mUpLoadState;
    private ArrayList<ImageTable> imageTables;
    private TextView mPosition;
    private PhotoViewPageAdapter adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_view_layout);
        initView();
        initData();
    }

    private void initView()
    {
        mImageViewPager = (ViewPager) findViewById(R.id.Image_ViewPager);
        mImageViewPager.setOnPageChangeListener(this);
        mRemake = (TextView) findViewById(R.id.Remake);
        mTime = (TextView) findViewById(R.id.TakePhoto_Time);
        mUpLoadState = (TextView) findViewById(R.id.UpLoadState);
        mPosition = (TextView) findViewById(R.id.Position);
    }

    private void initData()
    {
        Bundle bundle = getIntent().getBundleExtra("111");
        imageTables = bundle.getParcelableArrayList(PileInfoActivity.PILE_EXTRA_KEY);
        int currentPosition = getIntent().getIntExtra(PileInfoActivity.POSITION_EXTRA_KEY,-1);
        if (currentPosition==-1)
            currentPosition = 0;
        if (imageTables ==null)
        {
            UiUtils.showToast("加载失败");
            finish();
        }
        adapter = new PhotoViewPageAdapter(imageTables,this);
        mImageViewPager.setAdapter(adapter);
        mImageViewPager.setCurrentItem(currentPosition);
        mPosition.setText(String.format("%s/%s",currentPosition+1,imageTables.size()));
        if (imageTables.get(currentPosition).getUpLoadTime()>0) {
            mUpLoadState.setText("已上传");
        }
        else
        {
            mUpLoadState.setText("未上传");
        }
        mRemake.setText(imageTables.get(currentPosition).getRemake());
        mTime.setText(imageTables.get(currentPosition).getCreatTime());
    }


    public void deleteImage(View view)
    {
        showDialog();
    }

    private void todoDelete()
    {
        int currentPosition = mImageViewPager.getCurrentItem();
        DbCenter.deleteImage(imageTables.get(currentPosition).getPileId(),imageTables.get(currentPosition).getFileName());
        imageTables.remove(currentPosition);
        adapter.notifyDataSetChanged();
        UiUtils.showToast("删除成功");
        EventBus.getDefault().post(new NotificationImage(currentPosition,NotificationImage.DELETE));
    }

    private void showDialog()
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("确定要删除这张照片吗?");
        builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
                todoDelete();
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    public void upLoadImage(View view)
    {
        final int currentPosition = mImageViewPager.getCurrentItem();
        final ProgressDialog progressDialog = new ProgressDialog(this);
        final ImageTable imageTable = imageTables.get(currentPosition);
        if (imageTable.getIsSonicWave()==0)
        {
            progressDialog.setMessage("正在上传照片...");
            progressDialog.show();
            DataAcquisition.getInstance().uploadImage(Account.getRandomCode(),Account.getAccount(),new File(imageTable.getFilePath()),imageTable.getPileId(),
                    imageTable.getPlanNum(),imageTable.getPileNo(),imageTable.getType(),imageTable.getCreatTime(),imageTable.getRemake(),0,"0",this,new DataCallBack<ResponseData>()
                    {
                        @Override
                        public void processData(ResponseData data)
                        {
                            super.processData(data);
                            Log.d("processData: ",data.returnCode+"");
                            progressDialog.dismiss();
                            if (data.returnCode==0)
                            {
                                UiUtils.showToast("上传成功");
                                DbCenter.makeImageAsUpLoad(imageTable.getPileId(),imageTable.getFileName());
                                imageTables.get(currentPosition).setUpLoadTime(10);
                                adapter.notifyDataSetChanged();
                                EventBus.getDefault().post(new NotificationImage(currentPosition,NotificationImage.UPLOAD));
                            }
                            else if (data.returnCode == -1)
                            {
                                UpDateRandomCodeTask.startTask();
                                UiUtils.showToast("验证失效，请稍后再试");
                            }
                            else
                                UiUtils.showToast(String.format("上传失败(%s)",data.returnCode));
                        }
                    });
        }
        else
        {
            progressDialog.setMessage("正在上传波列图...");
            progressDialog.show();
            if (imageTable.getPileId() <= 0)
                imageTable.setPileId(10);

            DataAcquisition.getInstance().uploadImage(Account.getRandomCode(),Account.getAccount(),new File(imageTable.getFilePath()),imageTable.getPileId(),
                    imageTable.getPlanNum(),imageTable.getPileNo(),3,imageTable.getCreatTime(),imageTable.getRemake(),1,imageTable.getSectionId(),this,new DataCallBack<ResponseData>()
                    {
                        @Override
                        public void processData(ResponseData data)
                        {
                            super.processData(data);
                            Log.d("processData: ",data.returnCode+"");
                            progressDialog.dismiss();
                            if (data.returnCode==0)
                            {
                                UiUtils.showToast("上传成功");
                                DbCenter.makeImageAsUpLoad(imageTable.getPileId(),imageTable.getFileName());
                                imageTables.get(currentPosition).setUpLoadTime(10);
                                adapter.notifyDataSetChanged();
                                EventBus.getDefault().post(new NotificationImage(currentPosition,NotificationImage.UPLOAD));
                            }
                            else if (data.returnCode == -1)
                            {
                                UpDateRandomCodeTask.startTask();
                                UiUtils.showToast("验证失效，请稍后再试");
                            }

                            else if (data.returnCode==-98)
                            {
                                UiUtils.showToast("波列图重复");
                            }
                            else
                                UiUtils.showToast(String.format("上传失败(%s)",data.returnCode));
                        }
                    });
        }
    }
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
    {

    }
    //滚动到新条目 刷新信息
    @Override
    public void onPageSelected(int position)
    {
        ImageTable imageTable = imageTables.get(position);
        mRemake.setText(imageTable.getRemake());
        mTime.setText(imageTable.getCreatTime());
        if (imageTable.getUpLoadTime()>0)
            mUpLoadState.setText("已上传");
        else
            mUpLoadState.setText("未上传");
        mPosition.setText(String.format("%s/%s",position+1,imageTables.size()));
    }
    @Override
    public void onPageScrollStateChanged(int state)
    {

    }
    private class PhotoViewPageAdapter extends PagerAdapter
    {
        private ArrayList<ImageTable> imageTables;
        private Context context;
        private View[] imageViews;

        private PhotoViewPageAdapter(ArrayList<ImageTable> imageTables, Context context)
        {
            this.imageTables = imageTables;
            this.context = context;
            if (imageTables!=null)
                imageViews = new View[imageTables.size()];
        }

        @Override
        public int getCount()
        {
            if (imageTables==null)
                return 0;
            return imageTables.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object)
        {
            return view == object;
        }
        @Override
        public void destroyItem(ViewGroup container, int position, Object object)
        {
            container.removeView((View)object);
        }
        @Override
        public Object instantiateItem(ViewGroup container, int position)
        {
            View mBootView = View.inflate(context,R.layout.pile_photo_page_item_layout,null);
            ImageView photo = (ImageView) mBootView.findViewById(R.id.ImageView);
            Glide.with(context)
                    .load(new File(imageTables.get(position).getFilePath()))
                    .asBitmap()
                    .into(photo);
            imageViews[position] = mBootView;
            container.addView(mBootView);
            return mBootView;
        }
    }

    public void takeBack(View view)
    {
        finish();
    }


}